package com.cz.nongyetongv5.activity;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONObject;


import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Toast;

import com.cz.nongyetongv5.R;
import com.cz.nongyetongv5.adapter.config.CommonConstants;
import com.cz.nongyetongv5.adapter.dao.DatabaseHelper;
import com.cz.nongyetongv5.bean.Delbean;
import com.cz.nongyetongv5.bean.Town;
import com.cz.nongyetongv5.bean.User;
import com.cz.nongyetongv5.custom.dialog.CheckDialog;
import com.cz.nongyetongv5.custom.dialog.CustomDialog;
import com.cz.nongyetongv5.custom.dialog.DownloadDialog;
import com.cz.nongyetongv5.utils.ConfigUtil;
import com.cz.nongyetongv5.utils.Session;
import com.cz.nongyetongv5.utils.UpdateDateUtilEx;

public class CopyOfSyncActivity extends   FragmentActivity   {



	/**
	 * 登陆等待的对话框
	 */
	private CustomDialog waitUserLoginDialog = null;



	/**
	 * 验证用户的handler
	 */
	private Handler validateUser;



	private DatabaseHelper db = null;
	User user;

	public DownloadDialog downloadWaitDialog=null;
	public  CheckDialog checkDialog=null;
	private static final int SHOW=100;
	private static final int HIDE=101;
	private static final int  SYNCCOMP=200;
	private static final int  SHOWPLANCHECK=1100;
	private static final int  SYNCPLANCOMP=1200;

	private static final int  SHOWSUM=3100;


	protected void ionCreate(Bundle savedInstanceState) {


		//registSreenStatusReceiver();
		db = new DatabaseHelper(this, CommonConstants.DBNAME, null,
				CommonConstants.DATABASE_VERSION);


		user = (User) getIntent().getSerializableExtra("user");

		validateUser = new Handler(){
			@Override
			public void handleMessage(Message msg) {
				switch (msg.what) {
					case SHOW:
						if(downloadWaitDialog!=null&&downloadWaitDialog.isShowing())
							downloadWaitDialog.dismiss();
						if(checkDialog!=null&&checkDialog.isShowing()){
							checkDialog.dismiss();
							checkDialog=null;
						}
						if(waitUserLoginDialog!=null&& waitUserLoginDialog.isShowing())
						{  waitUserLoginDialog.dismiss();
							waitUserLoginDialog=null;
						}
						waitUserLoginDialog=new CustomDialog(CopyOfSyncActivity.this);
						waitUserLoginDialog.setWidthPercent(0.6F);
						waitUserLoginDialog.setMessage("正在加载,请稍后");
						waitUserLoginDialog.show();
						break;
					case SHOWSUM:
						if(downloadWaitDialog!=null&&downloadWaitDialog.isShowing())
							downloadWaitDialog.dismiss();
						if(checkDialog!=null&&checkDialog.isShowing()){
							checkDialog.dismiss();
							checkDialog=null;
						}
						if(waitUserLoginDialog!=null&& waitUserLoginDialog.isShowing())
						{  waitUserLoginDialog.dismiss();
							waitUserLoginDialog=null;
						}
						waitUserLoginDialog=new CustomDialog(CopyOfSyncActivity.this);
						waitUserLoginDialog.setWidthPercent(0.6F);
						waitUserLoginDialog.setMessage("正在分析数据,请稍后");
						waitUserLoginDialog.show();
						break;
					case HIDE:
						if(downloadWaitDialog!=null&&downloadWaitDialog.isShowing())
							downloadWaitDialog.dismiss();
						if(waitUserLoginDialog!=null&& waitUserLoginDialog.isShowing())
						{  waitUserLoginDialog.dismiss();
							waitUserLoginDialog=null;
						}
						break;
					case BARVAL:
						//					 BarBean data=(BarBean)msg.obj;
						//					 downloadWaitDialog.show();
						//					 downloadWaitDialog.setMessage(data.msg);
						//					 downloadWaitDialog.bar.setProgress(data.val);
						break;
					case BARVAL2:
						BarBean data=(BarBean)msg.obj;
						downloadWaitDialog.show();
						downloadWaitDialog.setMessage("基础数据更新中");
						downloadWaitDialog.bar.setProgress(data.val);
						break;
					case SYNCPLANCOMP:
						if(downloadWaitDialog!=null&&downloadWaitDialog.isShowing())
							downloadWaitDialog.dismiss();
						if(checkDialog!=null&&checkDialog.isShowing()){
							checkDialog.dismiss();
							checkDialog=null;
						}
						checkDialog=new CheckDialog(CopyOfSyncActivity.this);
						checkDialog.setWidthPercent(0.6F);
						checkDialog.setMessage("计划任务更新完成");
						checkDialog.setSingle("确定");
						checkDialog.show();
						break;
					case SHOWPLANCHECK:
						if(downloadWaitDialog!=null&&downloadWaitDialog.isShowing())
							downloadWaitDialog.dismiss();

						if(waitUserLoginDialog!=null&&waitUserLoginDialog.isShowing())
							waitUserLoginDialog.dismiss();
						if(checkDialog!=null&&checkDialog.isShowing()){
							checkDialog.dismiss();
							checkDialog=null;
						}
						checkDialog=new CheckDialog(CopyOfSyncActivity.this);
						checkDialog.setWidthPercent(0.6F);
						checkDialog.setMessage("计划任务有变化,请立即更新");
						checkDialog.setSingle("确定");
						checkDialog.setSingleListener(new OnClickListener(){
							@Override
							public void onClick(View arg0) {
								getPlans();
							}});

						checkDialog.show();
						break;
					case SYNCCOMP:

						downloadWaitDialog.dismiss();
						if(checkDialog!=null&&checkDialog.isShowing()){
							checkDialog.dismiss();
							checkDialog=null;
						}
						checkDialog=new CheckDialog(CopyOfSyncActivity.this);
						checkDialog.setWidthPercent(0.6F);
						checkDialog.setMessage("基础数据更新成功");
						checkDialog.setSingle("确定");
						checkDialog.setSingleListener(new OnClickListener(){
							@Override
							public void onClick(View arg0) {
								checkDialog.dismiss();
								checkPlan();
							}
						});
						checkDialog.show();
						break;
					case CHECKSYNC:

						if(checkDialog!=null&&checkDialog.isShowing()){
							checkDialog.dismiss();
							checkDialog=null;
						}
						checkDialog=new CheckDialog(CopyOfSyncActivity.this);
						checkDialog.setWidthPercent(0.6F);
						checkDialog.setSingleListener(new OnClickListener(){

							@Override
							public void onClick(View arg0) {
								// TODO Auto-generated method stub
								Session session=new Session(CopyOfSyncActivity.this,"doing");
								if(session.getString().equals("1"))
									sument2();
								else{
									checkDialog.dismiss();
								}
							}
						});
						checkDialog.setOnActionClickListener(new OnClickListener(){
							@Override
							public void onClick(View arg0) {
								checkDialog.dismiss();
								doLogin();

							}
						});
						checkDialog.show();
						break;


					case CHECKOTHER:  doOther();  break;
				}
			}
		};



		if(downloadWaitDialog!=null&& downloadWaitDialog.isShowing())
		{  downloadWaitDialog.dismiss();
			downloadWaitDialog=null;
		}
		downloadWaitDialog=new DownloadDialog(this);
		downloadWaitDialog.setWidthPercent(0.6F);
		downloadWaitDialog.setMessage("准备下载数据");

		Session session=new Session(CopyOfSyncActivity.this,"doing");
		session.setString("0");

		//check2();
		check3();

	}


	//计算数据
	private JSONArray checkRegions=null;
	private void sument2(){
		setMessage("",1,SHOWSUM);
		new Thread(new Runnable() {
			@Override
			public void run() {
				UpdateDateUtilEx dataUtil = new UpdateDateUtilEx(db,
						CopyOfSyncActivity.this, user);
				int sec=0;
				int result=dataUtil.updateTown(sec);

				setMessage("数据分析中",1,BARVAL);

				Log.d("rafe result",String.valueOf(result));
				setMessage("基础数据更新中",50,BARVAL2);
				int tick=50;
				while(result>0&&sec<16000){
					sec=sec+1000;
					tick++;
					if(tick>60)tick=60;

					setMessage("基础数据更新中",tick,BARVAL2);
					// int bar=(int) (((double)sec/(double)16000)*100);
					//setMessage("数据分析中",bar,BARVAL);
					result=dataUtil.updateTown(sec);
				}
				setMessage("基础数据更新中",60,BARVAL2);
				check3();

			}
		}).start();
	}
	private String getPlanDelTime(){

		SharedPreferences sharedPreferences= getSharedPreferences("deltime",MODE_PRIVATE);
		String name =sharedPreferences.getString("name", "");
		return name;
	}
	private void setPlanDelTime(String time){
		SharedPreferences sharedPreferences= getSharedPreferences("deltime",MODE_PRIVATE);
		SharedPreferences.Editor editor = sharedPreferences.edit();
		//用putString的方法保存数据
		editor.putString("name", time);
		//提交当前数据
		editor.commit();
	}

	private JSONObject otherSync=new JSONObject();
	private void check3(){

		new Thread(new Runnable() {
			@Override
			public void run() {
				UpdateDateUtilEx dataUtil = new UpdateDateUtilEx(db,
						CopyOfSyncActivity.this, user);
				JSONArray datas=  dataUtil.check3(user.getKnowRegion());
				otherSync=datas.optJSONObject(0);
				if(otherSync!=null){
					setMessage("",1,CHECKOTHER);
				}else{
					setMessage("",1,HIDE);
					checkPlan();
				}
			}
		}).start();
	}
	private void check2(){
		setMessage("",1,SHOWSUM);
		new Thread(new Runnable() {
			@Override
			public void run() {
				UpdateDateUtilEx dataUtil = new UpdateDateUtilEx(db,
						CopyOfSyncActivity.this, user);
				checkRegions=  dataUtil.check2(user.getKnowRegion());
				if(checkRegions.length()>0){
					setMessage("",1,HIDE);
					setMessage("",1,CHECKSYNC);
				}else{
					setMessage("",1,HIDE);
					check3();
				}
			}
		}).start();
	}
	private boolean checkBeijiandanwei(){
		String ent_code=user.getKnowRegion();
		if(ent_code.length()>8){ ent_code=ent_code.substring(0,8); }
		List<Town> towns= db.queryTownByCode(ent_code);

		UpdateDateUtilEx dataUtil = new UpdateDateUtilEx(db,
				CopyOfSyncActivity.this, user);
		String maxTime="";

		for(int i=0;i<towns.size();i++){
			Town town=towns.get(i);
			maxTime = db.queryEntMaxMotifyTime("BEIJIANDANWEI"+town.getCode(),"ADDTIME",town.getCode());
			maxTime = maxTime.replaceAll(" ", "%20");
			if(dataUtil.check(maxTime, town.getCode())){
				Log.d("rafe_checktime",town.getCode()+"?"+maxTime);
				return true;
			}
		}
		return false;

	}
	public static final int BARVAL=77;
	public static final int BARVAL2=67;
	public static final int CHECKSYNC=78;
	public static final int CHECKOTHER=79;
	public void setMessage(String msg,int val,int code){

		Message m= new Message();
		m.what=code;
		BarBean ben=new BarBean();
		ben.msg=msg;
		ben.val=val;
		m.obj=ben;
		validateUser.sendMessage(m);
	}


	class BarBean{
		public BarBean(){ }
		public int val=1;
		public String msg="";

	}
	// 处理登陆的方法


	private void doLogin() {
		Session session=new Session(CopyOfSyncActivity.this,"doing");
		session.setString("1");
		// 处理获取用户信息的线程
		Thread userLoginThread = new Thread(new Runnable() {
			@Override
			public void run() {

				if(checkRegions==null||checkRegions.length()<0){
					setMessage("未知错误",0,HIDE);
					return;
				}
				Log.d("rafe", "被检对象同步开始...");
				setMessage("正在同步被检对象信息",0,BARVAL);
				int tick=1;
				for(int i=0;i<checkRegions.length();i++){

					if(tick<50){
						tick++;
						setMessage("正在同步被检对象信息",tick,BARVAL2);
					}
					JSONObject town=checkRegions.optJSONObject(i);
					JSONObject townlocal = db.querySyncByCode(town.optString("code"));
					if(town.optInt("add_status",0)==1)
						sync_ent(townlocal,"add","下载"+town.optString("name")+"受检对象信息","add_time");
					if(town.optInt("modify_status",0)==1)
						sync_ent(townlocal,"modify","更新"+town.optString("name")+"受检对象信息","modify_time");
					if(town.optInt("delete_status",0)==1)
						del_ent("清理"+town.optString("name")+"受检对象信息","BEIJIANDANWEI",townlocal);
				}
				//   			  setMessage("正在校验受检对象数据",10,BARVAL);
				UpdateDateUtilEx dataUtil = new UpdateDateUtilEx(db, CopyOfSyncActivity.this, user);
				dataUtil.checkBack(user.getKnowRegion());
				//   			  setMessage("校验受检对象数据完成",100,BARVAL);

				Log.d("rafe", "被检对象同步完成...");

				//   			   Log.d("rafe", "抽样机构同步开始");
				//   			   sync_obj("CHOUYANJIGOU","add","下载抽样机构","ADDTIME");
				//   			   Log.d("rafe", "抽样机构同步完成...");
				//   			    Log.d("rafe", "检查单位同步开始");
				//  			   sync_obj("JIANCHADANWEI","add","下载检查单位","ADDTIME");
				// 			   Log.d("rafe", "检测单位同步完成...");
				// 			   Log.d("rafe", "监管人员同步开始");
				//			   sync_obj("JIANGUANRENYUAN","add","下载监管人员","ADDTIME");
				//			   Log.d("rafe", "监管人员同步完成...");
				//			   Log.d("rafe", "监管人员简化同步开始");
				//			   sync_obj("LINKMAN","add","下载联系人","ADDTIME");
				//			   Log.d("rafe", "监管人员简化位同步完成...");
				//
				//			   Log.d("rafe", "抽样机构更新开始");
				//   			   sync_obj("CHOUYANJIGOU","modify","更新抽样机构","MODIFYTIME");
				//   			   Log.d("rafe", "抽样机构更新完成...");
				//   			    Log.d("rafe", "检查单位更新开始");
				// 			   sync_obj("JIANCHADANWEI","modify","更新检查单位","MODIFYTIME");
				// 			   Log.d("rafe", "检测单位更新完成...");
				// 			   Log.d("rafe", "监管人员更新开始");
				//			   sync_obj("JIANGUANRENYUAN","modify","更新监管人员","MODIFYTIME");
				//			   Log.d("rafe", "监管人员更新完成...");
				//			   Log.d("rafe", "监管人员简化更新开始");
				//			   sync_obj("LINKMAN","modify","更新联系人","MODIFYTIME");
				//			   Log.d("rafe", "监管人员简化位更新完成...");

				//   			   del_ent("清理抽样机构","CHOUYANJIGOU",null);
				//   		       del_ent("清理检查单位","JIANCHADANWEI",null);
				// 			   del_ent("清理监管人员","JIANGUANRENYUAN",null);
				//			   del_ent("清理联系人","LINKMAN",null);
				sument2();

			}


		});
		userLoginThread.start();

	}


	private void doOther() {

		// 处理获取用户信息的线程
		Thread userLoginThread = new Thread(new Runnable() {
			@Override
			public void run() {
				JSONObject da=otherSync;
				if(da!=null){

					// if(da.optInt("ent_modify_status")==1 ){ }
					//  if(da.optInt("ent_delete_status")==1 ){ }
					setMessage("更新中",71,BARVAL2);
					if(da.optInt("department_add_status")==1 ){
						Log.d("rafe", "检查单位同步开始");
						sync_obj("JIANCHADANWEI","add","下载检查单位","ADDTIME");
						Log.d("rafe", "检测单位同步完成...");
						db.insertOrUpdateMobileSync(user.getKnowRegion(),"DEPART_ADDTIME");
					}
					setMessage("更新中",74,BARVAL2);
					if(da.optInt("department_modify_status")==1 ){
						Log.d("rafe", "检查单位更新开始");
						sync_obj("JIANCHADANWEI","modify","更新检查单位","MODIFYTIME");
						Log.d("rafe", "检测单位更新完成...");
						db.insertOrUpdateMobileSync(user.getKnowRegion(),"DEPART_MODIFYTIME");
					}
					setMessage("更新中",76,BARVAL2);
					if(da.optInt("department_delete_status")==1 ){
						del_ent("清理检查单位","JIANCHADANWEI",null);
						db.insertOrUpdateMobileSync(user.getKnowRegion(),"DEPART_DELETETIME");
					}
					setMessage("更新中",80,BARVAL2);
					if(da.optInt("detector_add_status")==1 ){

						Log.d("rafe", "抽样机构同步开始");
						sync_obj("CHOUYANJIGOU","add","下载抽样机构","ADDTIME");
						Log.d("rafe", "抽样机构同步完成...");
						db.insertOrUpdateMobileSync(user.getKnowRegion(),"DETECTOR_ADDTIME");
					}
					setMessage("更新中",82,BARVAL2);
					if(da.optInt("detector_modify_status")==1 ){

						Log.d("rafe", "抽样机构更新开始");
						sync_obj("CHOUYANJIGOU","modify","更新抽样机构","MODIFYTIME");
						Log.d("rafe", "抽样机构更新完成...");
						db.insertOrUpdateMobileSync(user.getKnowRegion(),"DETECTOR_MODIFYTIME");

					}
					setMessage("更新中",85,BARVAL2);
					if(da.optInt("detector_delete_status")==1 ){
						del_ent("清理抽样机构","CHOUYANJIGOU",null);
						db.insertOrUpdateMobileSync(user.getKnowRegion(),"DETECTOR_DELETETIME");

					}
					setMessage("更新中",87,BARVAL2);
					if(da.optInt("team_add_status")==1 ){

						Log.d("rafe", "监管人员同步开始");
						sync_obj("JIANGUANRENYUAN","add","下载监管人员","ADDTIME");
						Log.d("rafe", "监管人员同步完成...");
						db.insertOrUpdateMobileSync(user.getKnowRegion(),"TEAM_ADDTIME");

					}
					setMessage("更新中",89,BARVAL2);
					if(da.optInt("team_modify_status")==1 ){
						Log.d("rafe", "监管人员更新开始");
						sync_obj("JIANGUANRENYUAN","modify","更新监管人员","MODIFYTIME");
						Log.d("rafe", "监管人员更新完成...");
						db.insertOrUpdateMobileSync(user.getKnowRegion(),"TEAM_MODIFYTIME");
					}
					setMessage("更新中",91,BARVAL2);
					if(da.optInt("team_delete_status")==1 ){

						del_ent("清理监管人员","JIANGUANRENYUAN",null);
						db.insertOrUpdateMobileSync(user.getKnowRegion(),"TEAM_DELETETIME");
					}
					setMessage("更新中",93,BARVAL2);
					if(da.optInt("linkman_add_status")==1 ){
						Log.d("rafe", "监管人员简化同步开始");
						sync_obj("LINKMAN","add","下载联系人","ADDTIME");
						Log.d("rafe", "监管人员简化位同步完成...");
						db.insertOrUpdateMobileSync(user.getKnowRegion(),"LINKMAN_ADDTIME");
					}
					setMessage("更新中",95,BARVAL2);
					if(da.optInt("linkman_modify_status")==1 ){


						Log.d("rafe", "监管人员简化同步开始");
						sync_obj("LINKMAN","modify","更新联系人","MODIFYTIME");
						Log.d("rafe", "监管人员简化位同步完成...");
						db.insertOrUpdateMobileSync(user.getKnowRegion(),"LINKMAN_MODIFYTIME");
					}
					setMessage("更新中",97,BARVAL2);
					if(da.optInt("linkman_delete_status")==1 ){
						del_ent("清理联系人","LINKMAN",null);
						db.insertOrUpdateMobileSync(user.getKnowRegion(),"LINKMAN_DELETETIME");
					}
					setMessage("更新中",99,BARVAL2);
					setMessage("",1,HIDE);
					setMessage("",1,SYNCCOMP);
				}

			}
		});
		userLoginThread.start();

	}

	private void sync_obj(String table,String opt,String msg,String timefield){
		UpdateDateUtilEx dataUtil = new UpdateDateUtilEx(db,
				CopyOfSyncActivity.this, user);
		String maxTime = db.queryMaxMotifyTime(table,timefield,user.getKnowRegion());
		//测试移除
		maxTime="2015-09-10 12:00:00";

		maxTime = maxTime.replaceAll(" ", "%20");

		Log.d("rafe",table+"   "+maxTime);
		setMessage("正在"+msg+"信息 ",0,BARVAL);
		int start=0;
		int sum= dataUtil.sumAdd(table, start, maxTime, user.getKnowRegion(),opt);
		if(sum>0){
			while(start<sum){
				start+=20;
				int bar=(int) (((double)start/(double)sum)*100);
				if(bar>100){bar=100;}
				setMessage("正在"+msg+"信息 :"+bar+"%",bar,BARVAL);
				if(dataUtil.sumAdd(table, start, maxTime, user.getKnowRegion(),opt)<0){
					Log.d("rafe", msg+"异常退出");
					break;
				}
			}
			setMessage(msg+"信息完成",100,BARVAL);

		}

	}
	private void sync_obj2(String table,String opt,String msg,String timefield){
		UpdateDateUtilEx dataUtil = new UpdateDateUtilEx(db,
				CopyOfSyncActivity.this, user);
		String maxTime = db.queryMaxMotifyTime(table,timefield,user.getKnowRegion());
		//测试移除
		maxTime="2015-09-10 12:00:00";

		maxTime = maxTime.replaceAll(" ", "%20");

		Log.d("rafe",table+"   "+maxTime);
		setMessage("正在"+msg+"信息 ",0,BARVAL);
		int start=0;
		int sum= dataUtil.sumAdd(table, start, maxTime, user.getKnowRegion(),opt);
		if(sum>0){
			while(start<sum){
				start+=20;
				int bar=(int) (((double)start/(double)sum)*100);
				if(bar>100){bar=100;}
				setMessage("正在"+msg+"信息 :"+bar+"%",bar,BARVAL);
				if(dataUtil.sumAdd(table, start, maxTime, user.getKnowRegion(),opt)<0){
					Log.d("rafe", msg+"异常退出");
					break;
				}
			}
			setMessage(msg+"信息完成",100,BARVAL);

		}

	}


	private void sync_ent(JSONObject town,String opt,String msg,String timefield){
		UpdateDateUtilEx dataUtil = new UpdateDateUtilEx(db,
				CopyOfSyncActivity.this, user);

		String code=town.optString("code");

		if(code.length()<8)return;
		int start=0;
		Log.d("rafe_debug",String.valueOf(town.toString()));
		int sum= dataUtil.sum("BEIJIANDANWEI"+code.substring(0,8),0,town.optString(timefield),code,opt);
		setMessage("准备"+msg,0,BARVAL);
		if(sum>0){
			while(start<sum){
				start+=20;
				int bar=(int) (((double)start/(double)sum)*100);
				if(bar>100){bar=100;}
				setMessage("正在"+msg+":"+bar+"%",bar,BARVAL);

				int rcode=dataUtil.sum("BEIJIANDANWEI"+code.substring(0,8),0,town.optString(timefield),code,opt);
				Log.d("rafe rcode", rcode+"异常退出");
				if(rcode<0){
					Log.d("rafe", "异常退出");
					break;
				}
			}
			setMessage(msg+"完成",100,BARVAL);
		}


	}
	public String getVersion() {
		try {
			PackageManager manager = this.getPackageManager();
			PackageInfo info = manager.getPackageInfo(this.getPackageName(), 0);
			String version = info.versionName;
			return  version;
		} catch (Exception e) {

			return "1";
		}
	}
	private void del_ent(String msg,String table,JSONObject town){

		UpdateDateUtilEx dataUtil = new UpdateDateUtilEx(db,
				CopyOfSyncActivity.this, user);
		String maxtime="";
		String code="";
		if(town!=null){
			code=town.optString("code");
			if(code.length()<8){
				return;
			}
			table="BEIJIANDANWEI"+code.substring(0, 8);
			maxtime= town.optString("delete_time");
		}else{
			maxtime = db.queryEntMaxMotifyTime(table,"DELETETIME",user.getKnowRegion());
		}
		maxtime = maxtime.replaceAll(" ", "%20");
		setMessage("准备"+msg,0,BARVAL);
		int start=0;
		Delbean sum= dataUtil.sumDelect(table,start,maxtime,code);
		if(sum.getCount()>0){
			while(start<sum.getCount()){
				start+=20;
				int bar=(int) (((double)start/(double)sum.getCount())*100);
				if(bar>100){bar=100;}
				setMessage("正在"+msg+":"+bar+"%",bar,BARVAL);
				Delbean sum1= dataUtil.sumDelect(table,start,maxtime,code);
				if(sum1.getCount()<0){
					Log.d("rafe", msg+"异常退出");
					break;
				}
			}
		}
		setMessage(msg+"完成",100,BARVAL);


	}

	/**计划接口*/

	protected void getPlans(){
		setMessage("现实加载条",1,SHOW);

		//		 if(!db.hasTable("MONITOR_PLAN")){
		// 	         db.create( getResources().getString(
		// 				  R.string.table_monitorplan));
		// 	          Log.d("rafe","创建计划表");
		// 	      }
		//
		//		 if(!db.hasTable("MONITOR_PLAN_ENTS")){
		// 	         db.create( getResources().getString(
		// 				  R.string.table_monitorplan_ent));
		// 	          Log.d("rafe","创建计划对象表");
		// 	      }
		//
		Thread planThread = new Thread(new Runnable() {
			@Override
			public void run() {

				optPlan("add","下载");
				optPlan("modify","更新");
				optPlan("delete","删除");

				setMessage("关闭加载条",1,HIDE);
				setMessage("清除加载条",1,SYNCPLANCOMP);
			}});


		planThread.start();

	}

	private void checkPlan(){
		setMessage("",1,SHOW);
		new Thread(new Runnable() {
			@Override
			public void run() {
				String maxTime = db.queryMaxMotifyTime("MONITOR_PLAN","ADDTIME",
						user.getKnowRegion());
				maxTime = maxTime.replaceAll(" ", "T");
				Log.d("rafe plan maxTime",maxTime);
				UpdateDateUtilEx dataUtil = new UpdateDateUtilEx(db,
						CopyOfSyncActivity.this, user);
				JSONObject data=dataUtil.getPlanObject("0",0, maxTime, "add");
				if(data!=null&&data.optInt("totalCount",0)>0){
					setMessage("",1,HIDE);
					setMessage("",1,SHOWPLANCHECK);
				}else {
					setMessage("",1,HIDE);
					checkPlan2();

				}

			}
		}).start();
	}
	private void checkPlan2(){


		setMessage("",1,SHOW);
		new Thread(new Runnable() {
			@Override
			public void run() {
				String maxTime = db.queryMaxMotifyTime("MONITOR_PLAN","MODIFYTIME",
						user.getKnowRegion());

				maxTime = maxTime.replaceAll(" ", "T");
				Log.d("rafe plan MODIFYTime",maxTime);
				UpdateDateUtilEx dataUtil = new UpdateDateUtilEx(db,
						CopyOfSyncActivity.this, user);
				JSONObject data=dataUtil.getPlanObject("0",0, maxTime, "modify");
				if(data!=null&&data.optInt("totalCount",0)>0){
					setMessage("",1,HIDE);
					setMessage("",1,SHOWPLANCHECK);
				}else {
					setMessage("",1,HIDE);
					checkPlan3();
				}

			}
		}).start();
	}
	private void checkPlan3(){
		setMessage("",1,SHOW);

		new Thread(new Runnable() {
			@Override
			public void run() {

				String maxTime=getPlanDelTime();
				if(maxTime.equals("")){
					maxTime = db.queryMaxMotifyTime("MONITOR_PLAN","MODIFYTIME",
							user.getKnowRegion());
					maxTime = maxTime.replaceAll(" ", "T");

				}


				Log.d("rafe plan Delect Time",maxTime);


				UpdateDateUtilEx dataUtil = new UpdateDateUtilEx(db,
						CopyOfSyncActivity.this, user);
				JSONObject data=dataUtil.getPlanObject("0",0, maxTime, "delete");
				SimpleDateFormat sdf =   new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss");
				maxTime=sdf.format(new Date());
				setPlanDelTime(maxTime.replaceAll(" ", "T"));
				if(data!=null&&data.optInt("totalCount",0)>0){
					setMessage("",1,HIDE);
					setMessage("",1,SHOWPLANCHECK);
				}else   setMessage("",1,HIDE);


			}
		}).start();
	}



	private void optPlan(String opt,String msg){

		String timefield="ADDTIME";
		if(opt.equals("modify")){
			timefield="MODIFYTIME";
		}else if(opt.equals("delect")){
			timefield="DELETETIME";

		}
		String maxTime = db.queryMaxMotifyTime("MONITOR_PLAN",timefield,
				user.getKnowRegion());
		maxTime = maxTime.replaceAll(" ", "T");

		UpdateDateUtilEx dataUtil = new UpdateDateUtilEx(db,
				CopyOfSyncActivity.this, user);
		int start=0;
		int sum= dataUtil.sumPlan(start,maxTime,opt);
		if(sum>0){
			setMessage("正在"+msg+"计划信息 ",0,BARVAL);
			while(start<sum){
				start+=10;
				int bar=(int) (((double)start/(double)sum)*100);
				if(bar>100){bar=100;}
				setMessage("正在"+msg+"计划信息:"+bar+"%",bar,BARVAL);
				if(dataUtil.sumPlan(start,maxTime,opt)<0){
					Log.d("rafe", "异常退出");
					break;
				}
			}
			setMessage(msg+"计划信息完成",100,BARVAL);

		}





	}
}
